<template>
    <ModalCom v-bind="$attrs" width="800px" @open="modalOpen" :inner-loading="innerLoading" :footer="false" :ok-async="okAsync">
      <div class="text-right margin-bottom-16"><a-button @click="addRow">添加权限标识</a-button></div>
      <Table :is-page="false" ref="tabelRef" :edit-config="{mode: 'row', trigger: 'click'}" :data="dataList" :column="column" :operation="false">
        <template #item="{row}">
          <div>{{ powerKey(row) }}</div>
        </template>
        <template #operation="{row}">
          <a-button type="link" v-if="!row.edit" @click="edit(row)">编辑</a-button>
          <a-button type="link" v-else @click="okAsync(row)">确认</a-button>
          <a-button type="link" @click="delbutton(row)">删除</a-button>
        </template>
      </Table>
    </ModalCom>
</template>

<script setup>
import { reactive, ref, computed } from "vue"
// 跨级组件
import ModalCom from "@/components/modal/index.vue"
import Table from "@/components/table/index.vue"
// messge
import { message } from "ant-design-vue"
// 搜索和表格配置
import { column } from "./column"
// 校验函数
import { validateRequired, validatePassword } from "@/utils/index"
// api
import { permissionSave, buttonList, buttonEdit, buttonDel } from "@/api/menu"
// props
const props = defineProps({
  row: {
    type: Object,
    default: () => ({})
  }
})
const tabelRef = ref(null)
const dataList = ref([])

const addRow = async () => {
  const $table = tabelRef.value.vxeTableRef
  const record = { 
    name: "",
    key: "",
    router_key: '/cangguan'.substring(1), 
    menu_id: props.row.menu_id, 
    edit: true
  }
  const { row: newRow } = await $table.insert(record)
  await $table.setEditRow(newRow)
}

const edit = async (row) => {
  row.edit = true
  const $table = tabelRef.value.vxeTableRef
  await $table.setEditRow(row)
}

const powerKey = computed(() => {
  return (row) => {
    return '/cangguan'.substring(1) + '_' + (row.key || '')
  }
})

// formFieldsRef
const formFieldsRef = ref(null)
const state = reactive({
 
})

const innerLoading = () => {
  return new Promise((resolve, reject) => { // then，catch
    buttonList({menu_id: props.row.menu_id}).then(res => {
      dataList.value = res.content || []
      resolve()
    })
  })
}

const delbutton = (row) => {
  buttonDel({id:row.id}).then(() => {
    innerLoading()
  })
}

const useEdit = (row) => {
  buttonEdit({ name: row.name, key: row.name, id: row.id}).then(() => {
    row.edit = false
    tabelRef.value.vxeTableRef.clearEdit()
  })
}

const okAsync = (row) => {
  if(row.id) {
    useEdit(row)
    return
  }
  permissionSave(row).then(res => {
    row.id = res.content.id
    row.edit = false
    tabelRef.value.vxeTableRef.clearEdit()
  })
}
const modalOpen = () => {
    console.log('打开了')
}
</script>